package net.ecpt.hrm.services;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.entity.condition.EntityOperator;
import org.ofbiz.entity.util.EntityUtil;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ServiceUtil;
import org.ofbiz.wvtools.utils.ExcelPoiUtils;

import javolution.util.FastList;
import javolution.util.FastMap;

public class HrEmployeeRecordXlsServices {
    public static final String module = HrEmployeeRecordXlsServices.class.getName();


    /**
     * 导入
     */
    public static Map<String, Object> importXls(DispatchContext dctx, Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess();
	Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
	Delegator delegator = dctx.getDelegator();
	List<GenericValue> toBeStore = new ArrayList();
	List<String> messageList = new ArrayList<String>();
	List<Map<String, Object>> sheetList = (List<Map<String, Object>>) context.get("sheetList");
	LocalDispatcher dispatcher = dctx.getDispatcher();
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	String createBy = userLogin.getString("partyId");

	try {
	    int i = 0;
	   
	    for (Map<String, Object> row : sheetList) {
		i = i + 1;
		
			
			String id = ExcelPoiUtils.getCellString(row, 0);
			String name = ExcelPoiUtils.getCellString(row, 1);
			String gender_dictText = ExcelPoiUtils.getCellString(row, 2);
			String idCard = ExcelPoiUtils.getCellString(row, 3);
			String nationId_dictText = ExcelPoiUtils.getCellString(row, 4);
			String nativePlace = ExcelPoiUtils.getCellString(row, 5);
			String email = ExcelPoiUtils.getCellString(row, 6);
			String phone = ExcelPoiUtils.getCellString(row, 7);
			String departmentId_dictText = ExcelPoiUtils.getCellString(row, 8);
			String positionRank_dictText = ExcelPoiUtils.getCellString(row, 9);
			String jobLevelId_dictText = ExcelPoiUtils.getCellString(row, 10);
			String engageForm_dictText = ExcelPoiUtils.getCellString(row, 11);
			String workAge = ExcelPoiUtils.getCellString(row, 12);
			String beginDate = ExcelPoiUtils.getCellString(row, 13);
			String contTerm = ExcelPoiUtils.getCellString(row, 14);
			Timestamp conversionTime = ExcelPoiUtils.getCellTimestamp(row, 15);
			Timestamp beginContract = ExcelPoiUtils.getCellTimestamp(row, 16);
			Timestamp endContract = ExcelPoiUtils.getCellTimestamp(row, 17);
			String householdLocation = ExcelPoiUtils.getCellString(row, 18);
			Timestamp estimateBeginDate = ExcelPoiUtils.getCellTimestamp(row, 19);
			//编号,员工姓名,性别,身份证,民族,籍贯,邮箱,电话号码,所属部门,职级,职称,聘用形式,工龄,入职日期,合同期限,转正日期,合同起始日期,合同终止日期,户籍所在地,预计入职日期
			
			// 判断
			if (UtilValidate.isEmpty(name)) {
			    messageList.add("第" + (i + 1) + "行,姓名不能为空。");
			    continue;
			}

			// 判断
			if (UtilValidate.isEmpty(gender_dictText)) {
			    messageList.add("第" + (i + 1) + "行,性别不能为空。");
			    continue;
			}
			// 判断
			if (UtilValidate.isEmpty(idCard)) {
			    messageList.add("第" + (i + 1) + "行,身份证不能为空。");
			    continue;
			}
			// 判断
			if (UtilValidate.isEmpty(nationId_dictText)) {
			    messageList.add("第" + (i + 1) + "行,民族不能为空。");
			    continue;
			}
			// 判断
			if (UtilValidate.isEmpty(nativePlace)) {
			    messageList.add("第" + (i + 1) + "行,籍贯不能为空。");
			    continue;
			}
			// 判断
			if (UtilValidate.isEmpty(email)) {
			    messageList.add("第" + (i + 1) + "行,邮箱不能为空。");
			    continue;
			}
			// 判断
			if (UtilValidate.isEmpty(phone)) {
			    messageList.add("第" + (i + 1) + "行,电话号码不能为空。");
			    continue;
			}
			// 判断
			if (UtilValidate.isEmpty(departmentId_dictText)) {
			    messageList.add("第" + (i + 1) + "行,所属部门不能为空。");
			    continue;
			}
			
			// 判断
			if (UtilValidate.isEmpty(positionRank_dictText)) {
			    messageList.add("第" + (i + 1) + "行,职级不能为空。");
			    continue;
			}
			// 判断
			if (UtilValidate.isEmpty(jobLevelId_dictText)) {
			    messageList.add("第" + (i + 1) + "行,职称不能为空。");
			    continue;
			}
			// 判断
			if (UtilValidate.isEmpty(engageForm_dictText)) {
			    messageList.add("第" + (i + 1) + "行,聘用形式不能为空。");
			    continue;
			}
			if (UtilValidate.isEmpty(workAge)) {
			    messageList.add("第" + (i + 1) + "行,工龄不能为空。");
			    continue;
			}
			// 判断
			if (UtilValidate.isEmpty(beginDate)) {
			    messageList.add("第" + (i + 1) + "行,入职日期不能为空。");
			    continue;
			}
			
			// 判断
			if (UtilValidate.isEmpty(contTerm)) {
			    messageList.add("第" + (i + 1) + "行,合同期限不能为空。");
			    continue;
			}
			if (UtilValidate.isEmpty(conversionTime)) {
			    messageList.add("第" + (i + 1) + "行,转正日期不能为空。");
			    continue;
			}			
			// 判断contTerm
			if (UtilValidate.isEmpty(beginContract)) {
			    messageList.add("第" + (i + 1) + "行,合同起始日期不能为空。");
			    continue;
			}
			
			if (UtilValidate.isEmpty(endContract)) {
			    messageList.add("第" + (i + 1) + "行,合同终止日期不能为空。");
			    continue;
			}
			
			if (UtilValidate.isEmpty(householdLocation)) {
			    messageList.add("第" + (i + 1) + "行,户籍所在地不能为空。");
			    continue;
			}
			
			// 判断
			if (UtilValidate.isEmpty(estimateBeginDate)) {
			    messageList.add("第" + (i + 1) + "行,预计入职日期不能为空。");
			    continue;
			}
			
			// 创建
			GenericValue entity = null;
			if (UtilValidate.isNotEmpty(id)) {
			   
			    List<GenericValue> entityList = delegator.findByAnd("HrEmployeeRecord",
					    UtilMisc.toMap("id", id), null, false);
				    entity = EntityUtil.getFirst(entityList);
				if (UtilValidate.isEmpty(entity)) {
						 id = delegator.getNextSeqId("HrEmployeeRecord");
						 entity = delegator.makeValue("HrEmployeeRecord", UtilMisc.toMap("id", id));
						 entity.set("statusId", "0");
							entity.set("createBy", createBy);
							entity.set("createDate", nowTimestamp);
						}    
			}else  {
			    id = delegator.getNextSeqId("HrEmployeeRecord");
			    entity = delegator.makeValue("HrEmployeeRecord", UtilMisc.toMap("id", id));
			    entity.set("statusId", "0");
				entity.set("createBy", createBy);
				entity.set("createDate", nowTimestamp);
			}  
			
			
			List<GenericValue> hrDepartmentInfo = delegator.findByAnd("HrDepartment", UtilMisc.toMap("name", departmentId_dictText),null, false);
			GenericValue hrDepartment =EntityUtil.getFirst(hrDepartmentInfo);
			String departmentId = hrDepartment.getString("departmentId");
			
			String gender = ExcelPoiUtils.getDataDictionaryCode(delegator, "USER_SEX",gender_dictText);
			String nationId = ExcelPoiUtils.getDataDictionaryCode(delegator, "ETHNICITY",nationId_dictText);
			String engageForm = ExcelPoiUtils.getDataDictionaryCode(delegator, "WORK_TYPE",engageForm_dictText);
			String positionRank = ExcelPoiUtils.getDataDictionaryCode(delegator, "POSITION_RANK",positionRank_dictText);
			String jobLevelId = ExcelPoiUtils.getDataDictionaryCode(delegator, "JOB_LEVEL",jobLevelId_dictText);
			
			
			
			
			entity.set("name", name);
			entity.set("gender", gender);
			entity.set("idCard", idCard);
			entity.set("nationId", nationId);
			entity.set("nativePlace", nativePlace);
			entity.set("email", email);
			entity.set("phone", phone);
			entity.set("departmentId", departmentId);
			entity.set("positionRank", positionRank);
			entity.set("jobLevelId", jobLevelId);
			entity.set("engageForm", engageForm);
			entity.set("workAge", workAge);
			entity.set("beginDate", beginDate);
			entity.set("contTerm", contTerm);
			entity.set("conversionTime", conversionTime);
			entity.set("beginContract", beginContract);
			entity.set("endContract", endContract);
			entity.set("householdLocation", householdLocation);
			entity.set("estimateBeginDate", beginDate);
			
			toBeStore.add(entity);
			
			
		}
	    
	    delegator.storeAll(toBeStore);
	    result.put("messageList", messageList);
	} catch (GenericEntityException e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }

    /**
     * 导出
     */

    public static Map<String, Object> exportXls(DispatchContext dctx, Map<String, ? extends Object> context) {
	Delegator delegator = dctx.getDelegator();
	String ids = (String) context.get("ids");
	List<String> baseIdList = FastList.newInstance();
	if (UtilValidate.isNotEmpty(ids)) {
	    baseIdList = Arrays.asList(ids.split(";"));
	}
	Map<String, Object> result = ServiceUtil.returnSuccess();

	EntityCondition mainCond = null;
	List<EntityCondition> andExprs = FastList.newInstance();
	//andExprs.add(EntityCondition.makeCondition("parentProductId", EntityOperator.EQUALS, "_NA_"));
	if (UtilValidate.isNotEmpty(baseIdList))
	    andExprs.add(EntityCondition.makeCondition("id", EntityOperator.IN, baseIdList));
	if (andExprs.size() > 0)
	    mainCond = EntityCondition.makeCondition(andExprs, EntityOperator.AND);

	try {
	    List<GenericValue> entityList = delegator.findList("HrEmployeeRecord", mainCond, null, null, null, true);

	    List<Map<String, Object>> list = FastList.newInstance();
	    Map<String, Object> keyMap = FastMap.newInstance();
	    keyMap.put("0", "id");
	    keyMap.put("1", "name");
	    keyMap.put("2", "gender");
	    keyMap.put("3", "phone");
	    keyMap.put("4", "departmentId");
	    keyMap.put("5", "engageForm");
	    keyMap.put("6", "workAge");
	    keyMap.put("7", "beginDate");
	    keyMap.put("8", "contTerm");
	    keyMap.put("9", "conversionTime");
	    keyMap.put("10", "beginContract");
	    keyMap.put("11", "endContract");
	    keyMap.put("12", "householdLocation");
	    keyMap.put("13", "nameEn");
	    keyMap.put("14", "age");
	    keyMap.put("15", "idCard");
	    keyMap.put("16", "birthday");
	    keyMap.put("17", "nationId");
	    keyMap.put("18", "wedlock");
	    keyMap.put("19", "politicId");
	    keyMap.put("20", "nativePlace");
	    keyMap.put("21", "household");
	    keyMap.put("22", "companyEmail");
	    keyMap.put("23", "email");
	    keyMap.put("24", "address");
	    keyMap.put("25", "postCode");
	    keyMap.put("26", "emergencyContact");
	    keyMap.put("27", "contactRelationship");
	    keyMap.put("28", "contactNumber");
	    keyMap.put("29", "tiptopDegree");
	    keyMap.put("30", "specialty");
	    keyMap.put("31", "school");
	    keyMap.put("32", "masterSpecialty");
	    keyMap.put("33", "masterSchool");
	    keyMap.put("34", "bankCard");
	    keyMap.put("35", "bankOfDeposit");
	    keyMap.put("36", "jobLevel");
	    keyMap.put("37", "companyName");
	    keyMap.put("38", "categoryId");
	    keyMap.put("39", "positionRank");
	    keyMap.put("40", "positionName");
	    keyMap.put("41", "reportTo");
	    keyMap.put("42", "workAddress");
	    keyMap.put("43", "workState");
	    keyMap.put("44", "notWorkDate");
	    
	    
	    String headers = "编号,员工姓名,性别,电话号码,所属部门,聘用形式,"
			    + "工龄,入司日期,合同期限,转正日期,合同起始日期,合同终止日期,户籍所在地,英文名,年龄,身份证号码,"
			    + "出生日期,民族,婚姻状况,政治面貌,籍贯,户籍类型,公司邮箱,个人邮箱,联系地址,邮编,紧急联系人,"
			    + "联系人关系,联系人电话,最高学历,所属专业,毕业院校,研究生所属专业,研究生毕业院校,银行卡号,开户行,职称,"
			    + "合同关系公司,员工分类,职级,现任岗位,直属上级,工作地点,员工状态,离职日期";
	    result.put("headers", headers);

	    
	    for (GenericValue entity : entityList) {
	    	//SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			Map<String, Object> map = FastMap.newInstance();
			String id = entity.getString("id");

			String name = entity.getString("name");
			String gender = entity.getString("gender");
			String gender_dictText = ExcelPoiUtils.getDataDictionaryDescription(delegator, "USER_SEX", gender);

			String phone = entity.getString("phone");
			String departmentId = entity.getString("departmentId");
			String departmentId_dictText = "";
			if(UtilValidate.isNotEmpty(departmentId)) {
			    List<GenericValue> hrDepartmentInfo = delegator.findByAnd("HrDepartment",
					UtilMisc.toMap("departmentId", departmentId), null, false);
			    if(UtilValidate.isNotEmpty(hrDepartmentInfo)) {
				GenericValue hrDepartment = EntityUtil.getFirst(hrDepartmentInfo);
				departmentId_dictText = hrDepartment.getString("name");
			    }
			}
			

			String engageForm = entity.getString("engageForm");
			String engageForm_dictText = ExcelPoiUtils.getDataDictionaryDescription(delegator, "WORK_TYPE",
				engageForm);
			

			String workAge = entity.getString("workAge");
			Timestamp beginDate = entity.getTimestamp("beginDate");
			//String beginDate = beginDate_tiem.toString().substring(0,10);
			//String beginDate = df.format(beginDate_tiem);
			
			String contTerm = entity.getString("contTerm");
			Timestamp conversionTime = entity.getTimestamp("conversionTime");
			//String conversionTime = conversionTime_tiem.toString().substring(0,10);
			//String conversionTime = df.format(conversionTime_tiem);
			
			Timestamp beginContract = entity.getTimestamp("beginContract");
			//String beginContract = beginContract_tiem.toString().substring(0,10);
			//String beginContract = df.format(beginContract_tiem);
			
			Timestamp endContract = entity.getTimestamp("endContract");
			//String endContract = endContract_tiem.toString().substring(0,10);
			//String endContract = df.format(endContract_tiem);
			
			String householdLocation = entity.getString("householdLocation");
			String nameEn = entity.getString("nameEn");
			String age = entity.getString("age");
			String idCard = entity.getString("idCard");
			
			Timestamp birthday = entity.getTimestamp("birthday");
			//String birthday = birthday_tiem.toString().substring(0,10);
			//String birthday = df.format(birthday_tiem);
			
			String nationId = entity.getString("nationId");
			String nationId_dictText = ExcelPoiUtils.getDataDictionaryDescription(delegator, "ETHNICITY", nationId);

			String wedlock = entity.getString("wedlock");
			String wedlock_dictText = ExcelPoiUtils.getDataDictionaryDescription(delegator, "EMP_MARITAL_STATUS",
				wedlock);
			String politicId = entity.getString("politicId");
			String politicId_dictText = ExcelPoiUtils.getDataDictionaryDescription(delegator, "EMP_PARTY",
				politicId);
			String nativePlace = entity.getString("nativePlace");
			String household = entity.getString("household");
			String household_dictText = ExcelPoiUtils.getDataDictionaryDescription(delegator, "HOUSEHOLD",
				household);
			String companyEmail = entity.getString("companyEmail");
			String email = entity.getString("email");
			String address = entity.getString("address");
			String postCode = entity.getString("postCode");
			String emergencyContact = entity.getString("emergencyContact");
			String contactRelationship = entity.getString("contactRelationship");
			String contactNumber = entity.getString("contactNumber");
			String tiptopDegree = entity.getString("tiptopDegree");
			String tiptopDegree_dictText = ExcelPoiUtils.getDataDictionaryDescription(delegator, "EMP_EDUCATION",
				tiptopDegree);
			String specialty = entity.getString("specialty");
			String school = entity.getString("school");
			String masterSpecialty = entity.getString("masterSpecialty");
			String masterSchool = entity.getString("masterSchool");
			String bankCard = entity.getString("bankCard");
			String bankOfDeposit = entity.getString("bankOfDeposit");
			String jobLevel = entity.getString("jobLevel");
		
			String companyId = entity.getString("companyName");
			String companyId_dictText = ExcelPoiUtils.getDataDictionaryDescription(delegator, "PARTNER_COM_TYPE",
					companyId);

			String categoryId = entity.getString("categoryId");
			String categoryId_dictText = ExcelPoiUtils.getDataDictionaryDescription(delegator, "STAFF_SORT",
				categoryId);

			String positionRank = entity.getString("positionRank");
			String positionRank_dictText = ExcelPoiUtils.getDataDictionaryDescription(delegator, "POSITION_RANK",
				positionRank);
			String positionName = entity.getString("positionName");
			String reportTo = entity.getString("reportTo");
			String workAddress = entity.getString("workAddress");
			String workState = entity.getString("workState");
			Timestamp notWorkDate = entity.getTimestamp("notWorkDate");
			//String notWorkDate = notWorkDate_tiem.toString().substring(0,10);
			//String notWorkDate = df.format(notWorkDate_tiem);

			map.put("id", id);
			map.put("name", name);
			map.put("gender", gender_dictText);
			map.put("phone", phone);
			map.put("departmentId", departmentId_dictText);
			map.put("engageForm", engageForm_dictText);
			map.put("workAge", workAge);
			map.put("beginDate", beginDate);
			map.put("contTerm", contTerm);
			map.put("conversionTime", conversionTime);
			map.put("beginContract", beginContract);
			map.put("endContract", endContract);
			map.put("householdLocation", householdLocation);
			map.put("nameEn", nameEn);
			map.put("age", age);
			map.put("idCard", idCard);
			map.put("birthday", birthday);
			map.put("nationId", nationId_dictText);
			map.put("wedlock", wedlock_dictText);
			map.put("politicId", politicId_dictText);
			map.put("nativePlace", nativePlace);
			map.put("household", household_dictText);
			map.put("companyEmail", companyEmail);
			map.put("email", email);
			map.put("address", address);
			map.put("postCode", postCode);
			map.put("emergencyContact", emergencyContact);
			map.put("contactRelationship", contactRelationship);
			map.put("contactNumber", contactNumber);
			map.put("tiptopDegree", tiptopDegree_dictText);
			map.put("specialty", specialty);
			map.put("school", school);
			map.put("masterSpecialty", masterSpecialty);
			map.put("masterSchool", masterSchool);
			map.put("bankCard", bankCard);
			map.put("bankOfDeposit", bankOfDeposit);
			map.put("jobLevel", jobLevel);
			map.put("companyName", companyId_dictText);
			map.put("categoryId", categoryId_dictText);
			map.put("positionRank", positionRank_dictText);
			map.put("positionName", positionName);
			map.put("reportTo", reportTo);
			map.put("workAddress", workAddress);
			map.put("workState", workState);
			map.put("notWorkDate", notWorkDate);

			list.add(map);
		    }
	    result.put("list", list);
	    result.put("keyMap", keyMap);
	} catch (GenericEntityException e) {
	    Debug.logError(e.getMessage(), module);
	}
	return result;
    }

    
}
